package projects.android.sms.activities;

import java.security.interfaces.RSAPublicKey;
import java.util.ArrayList;
import java.util.List;

import projects.android.sms.R;
import projects.android.sms.db.DBHandle;
import projects.android.sms.encrypter.Encrypter;
import projects.android.sms.object.SMS;
import projects.android.sms.receiver.SMSBroadcastReceiver;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Activity providing a simple UI for letting the user pick a telephone number out of his contacts and send an encrypted
 * SMS. If the public key of the recipient has not been received yet, a public key request is sent first. Afterwards,
 * recipient automatically send back its public key (if it has installed the app) and a notification is generated. Then
 * the user can send the encrypted message.
 * 
 * @author Thomas Jaeger
 * @author Mario Kraml
 * @author Tassilo Posegga
 * @author Robert Schenkenfelder
 * 
 */
public class EncryptMySMSActivity extends Activity {

	private static final int CONTACT_PICKER_RESULT = 1001;

	private ImageButton btContacts;
	private ImageButton btSend;
	private EditText etPhone;
	private EditText etMessage;

	final String TAG = "EncryptMySMSActivity";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sms_new_view);

		etPhone = (EditText) findViewById(R.id.et_phone);
		etMessage = (EditText) findViewById(R.id.et_message);

		btContacts = (ImageButton) findViewById(R.id.bt_contacts);
		btContacts.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				doLaunchContactPicker();
				disableButton(btContacts);
			}
		});

		btSend = (ImageButton) findViewById(R.id.bt_send);
		btSend.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				sendSMS();
				disableButton(btSend);
			}
		});
	}

	/**
	 * Sends a SMS to the phone number which is currently typed in the phone number text field with the message which is
	 * currently typed in the message field. Does the public key handling first if this has not been done with the
	 * chosen recipient before.
	 */
	private void sendSMS() {
		String sMessage = etMessage.getText().toString();
		String sNumber = etPhone.getText().toString();

		if (sMessage.length() < 1) {
			makeToast("No message");
			return;
		}
		if (sNumber.length() < 1) {
			makeToast("No valid phone number");
			return;
		}

		// Check if db entry exists
		DBHandle db = DBHandle.getInstance(getApplicationContext());
		RSAPublicKey publicKey = db.getPublicKey(getApplicationContext(), sNumber);

		// No entry was found
		if (publicKey == null) {
			// send public key request
			String sPublicKeyRequest = SMSBroadcastReceiver.PUBLIC_KEY_REQUEST_TAG + SMSBroadcastReceiver.ENCRYPT_TAG;
			SmsManager sms = SmsManager.getDefault();
			sms.sendTextMessage(sNumber, null, sPublicKeyRequest, null, null);
			Log.e(TAG, "Public key request sent to " + sNumber);
			makeToast("Public key request sent. You will get a Notification when you have received the public key of the user. After that you can send encrypted messages to the user.");
			return;
		}

		SmsManager sms = SmsManager.getDefault();
		try {
			// send text message encrypted with public key from recipient
			sms.sendTextMessage(
					sNumber,
					null,
					Encrypter.encrypt(sMessage,
							DBHandle.getInstance(getApplicationContext())
									.getPublicKey(getApplicationContext(), sNumber))
							+ SMSBroadcastReceiver.ENCRYPT_TAG, null, null);
			// store text message encrypted with own public key
			SMS newMessage = new SMS(Encrypter.encrypt(sMessage, DBHandle.getInstance(getApplicationContext())
					.getOwnPublicKey()), sNumber, System.currentTimeMillis(), false);
			db.addMessage(newMessage);
			makeToast("Message: \n\n" + sMessage + "\n has been sent");
		} catch (Exception e1) {
			makeToast("Message: \n\n" + sMessage + "\n has NOT been sent");
			e1.printStackTrace();
		}
	}

	/**
	 * Disables the pressed button for 5 seconds
	 */
	private void disableButton(final ImageButton ib) {
		new CountDownTimer(3500, 500) {
			private int i = -45;

			@Override
			public void onTick(long millisUntilFinished) {
				ib.setClickable(false);
				ib.setAlpha(i += 50);
				if (i >= 255) {
					ib.setClickable(true);
				}
			}

			@Override
			public void onFinish() {
			}
		}.start();
	}

	/**
	 * Simply displays a toast with a given message.
	 * 
	 * @param toastText
	 *            The text to be shown in the toast.
	 */
	private void makeToast(String toastText) {
		LayoutInflater inflater = getLayoutInflater();
		View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));

		ImageView image = (ImageView) layout.findViewById(R.id.image);
		image.setImageResource(R.drawable.ic_menu_login);
		TextView text = (TextView) layout.findViewById(R.id.text);
		text.setText(toastText);

		final Toast toast = new Toast(getApplicationContext());
		toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);

		toast.setDuration(Toast.LENGTH_LONG);
		toast.setView(layout);
		toast.show();
	}

	// ////////////////////////////////////////////////////////////////////////////////////
	// Contact picker
	// ////////////////////////////////////////////////////////////////////////////////////

	/**
	 * Launches the contact picker intent.
	 */
	private void doLaunchContactPicker() {
		Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
		startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case CONTACT_PICKER_RESULT:
				Cursor cursor = null;
				String phoneNumber = "";
				List<String> allNumbers = new ArrayList<String>();
				int phoneIdx = 0;
				try {
					Uri result = data.getData();
					String id = result.getLastPathSegment();
					cursor = getContentResolver().query(Phone.CONTENT_URI, null, Phone.CONTACT_ID + "=?",
							new String[] { id }, null);
					phoneIdx = cursor.getColumnIndex(Phone.DATA);
					if (cursor.moveToFirst()) {
						while (cursor.isAfterLast() == false) {
							phoneNumber = cursor.getString(phoneIdx);
							allNumbers.add(phoneNumber);
							cursor.moveToNext();
						}
					} else {
						// no results actions
					}
				} catch (Exception e) {
					// error actions
				} finally {
					if (cursor != null) {
						cursor.close();
					}

					final CharSequence[] items = allNumbers.toArray(new String[allNumbers.size()]);
					AlertDialog.Builder builder = new AlertDialog.Builder(this);
					builder.setTitle("Choose a number");
					builder.setItems(items, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int item) {
							String selectedNumber = items[item].toString();
							etPhone.setText(selectedNumber);
						}
					});
					AlertDialog alert = builder.create();
					if (allNumbers.size() > 1) {
						alert.show();
					} else {
						String selectedNumber = phoneNumber.toString();
						etPhone.setText(selectedNumber);
					}

					if (phoneNumber.length() == 0) {
						// no numbers found actions
					}
				}
				break;
			}
		} else {
			// activity result error actions
		}
	}
}